var client;
var MaxMenuNum = 30;
var menuAry;
var public;
var recommendTarget;
var lastRecommend;

jQuery.scope = function(target,func){ return function() { return func.apply(target,arguments);}};

var UserSetting = function() {
  var _isOwner = false;

  /**
   * isOwner
   * 現在のviewerがownerであるかどうかを示す
   */
  this.isOwner = function() {
    return _isOwner;
  };
  
  /**
   * getCurrentView
   * 現在のviewを文字列で返す
   */
  this.getCurrentView = function() {
    return gadgets.views.getCurrentView().getName();
  };
  /**
   * initialize
   * 初回に実行するメソッド
   */
  this.initialize = function() {
    this.checkViewerIsOwner();
    this.fetchOwnerStoredData();
  };

  this.initializeForProfile = function () {
    this.fetchOwnerStoredData();
  };

  /**
   * 現在のviewerがownerであるかどうかを確認する
   */
  this.checkViewerIsOwner = function() {
    $.getData('/people/@viewer/@self', {}, $.scope(this, this.checkViewerIsOwner_Result));
  };
  
  this.checkViewerIsOwner_Result = function(people) {
    var person = people[0];  
    _isOwner = person.isOwner;
    if (this.isOwner()) {
      this.activateSetting();
    }
  };

  /**
   * id:settingで囲まれたフォームを有効化する
   */
  this.activateSetting = function() {
    $("#setting").show();
  };

  this.showForProfile = function ()
  {
    // 非公開
    if (public == 3) {
      $('#recommendFood').html('非公開設定になっています。');
      return;
    }
    
    // 全体に公開
    if (public == 1) {
      this.showBySetting();
      return ;
    }
    
    if (public == 2) {
      $('#recommendFood').html('マイミクへの公開機能は開発中です。');
      return;
    }
  };

  this.showBySetting = function ()
  {
    
    if (recommendTarget.checkBreakfast) {
      $('#breakfast').show();
    } else {
      $('#breakfast').hide();
    }
    
    if (recommendTarget.checkLunch) {
      $('#lunch').show();
    } else {
      $('#lunch').hide();
    }
    
    if (recommendTarget.checkDinner) {
      $('#dinner').show();
    } else {
      $('#dinner').hide();
    }
    
    $('#lastdate').show();
    
    $('#breakfastData').html(lastRecommend.breakfast);
    $('#lunchData').html(lastRecommend.lunch);
    $('#dinnerData').html(lastRecommend.dinner);
    $('#lastdateData').html(lastRecommend.date);
    
    $('#loading').hide();
  };

  /**
   * fetchStoredData
   * 永続化データを取得する
   */
  this.fetchOwnerStoredData = function() {
    $.getData('/appdata/@owner/@self', {}, $.scope(this, this.fetchOwnerStoredData_Result));
  };
  
  this.fetchOwnerStoredData_Result = function(data) {
    var that = this;
    $.each(data, function(userId, data) {
      that.setFoodMenus(data);
      that.setPublic(data);
      that.setRecommendTarget(data);
      that.setLastRecommend(data);
    
    });
    
    if (this.getCurrentView() != 'profile') {
      this.showBySetting();
    } else {
      this.showForProfile();
    }
  };


  this.getDefaultFoodMenu = function ()
  {
    var menus = new Array();

    menus[0] = 'ラーメン';
    menus[1] = 'とんかつ';
    menus[2] = 'ハンバーグ';
    menus[3] = '中華';
    menus[4] = '和食';
    menus[5] = '洋食';
 
    return menus;
  }

  this.getDefaultRecommendTarget = function ()
  {
      var recommendTarget = new Object();
      recommendTarget.checkBreakfast = true;
      recommendTarget.checkLunch = true;
      recommendTarget.checkDinner = true;
      return recommendTarget;
  }

  this.getDefaultLastRecommend = function ()
  {
      var lastRecommend = new Object();
      lastRecommend.breakfast = 'まだ決めてません。';
      lastRecommend.lunch = 'まだ決めてません。';
      lastRecommend.dinner = 'まだ決めてません。';
      lastRecommend.date = 'まだおすすめしていません。';
      return lastRecommend;
  }

  // メニューの設定
  this.setFoodMenus = function (data)
  {
    if (data.foodMenusData == undefined || data.foodMenusData == null || data.foodMenusData.length < 1) {
      menuAry = this.getDefaultFoodMenu();
    } else {
      menuAry = data.foodMenusData;
    }

    var foodMenuTag = '<table>';
    
    foodMenuTag += '<tr>';
    
    for (var i = 0; i < menuAry.length; i++) {
      var labelIndex = (i % 3 == 0) ? 3 : (i % 3);
      foodMenuTag += '<th class="foodMenuLabel'+labelIndex+'">メニュー'+(i+1)+'</th>';
      foodMenuTag += '<td class="foodMenuData'+labelIndex+'"><input type="text" id="foodMenu'+i+'" value="'+menuAry[i]+'" /></td>';
      
      if ((i + 1) % 3 == 0 && (i + 1) != MaxMenuNum) {
        foodMenuTag += '</tr><tr>'
      }
    }

    for (; i < MaxMenuNum; i++) {
      foodMenuTag += '<th class="foodMenuLabel'+labelIndex+'">メニュー'+(i+1)+'</th>';
      foodMenuTag += '<td class="foodMenuData'+labelIndex+'"><input type="text" id="foodMenu'+i+'" value="" /></td>';

      if ((i + 1) % 3 == 0 && (i + 1) != MaxMenuNum) {
        foodMenuTag += '</tr><tr>'
      }
    }

    foodMenuTag += '</tr></table>';
    
    $('#foodMenus').html(foodMenuTag);
  };

  // 公開範囲
  this.setPublic = function (data)
  {
    if (data.public == undefined || data.public == null) {
      public = 3;
    } else {
      public = data.public;
    }
    $('#public').val(public);
  };

  // おすすめ対象
  this.setRecommendTarget = function (data)
  {
    if (data.recommendTarget == undefined || data.recommendTarget == null) {
      recommendTarget = this.getDefaultRecommendTarget();
    } else {
      recommendTarget = data.recommendTarget;
    }
    
    if (recommendTarget.checkBreakfast) {
      $('#checkBreakfast').attr('checked', true);
    }
    
    if (recommendTarget.checkLunch) {
      $('#checkLunch').attr('checked', true);
    }
    
    if (recommendTarget.checkDinner) {
      $('#checkDinner').attr('checked', true);
    }
  };
  
  // 直近のおすすめ結果
  this.setLastRecommend = function (data)
  {
    if (data.lastRecommend == undefined || data.lastRecommend == null) {
      lastRecommend = this.getDefaultLastRecommend();
    } else {
      lastRecommend = data.lastRecommend;
    }
  }

  /**
   * putStoredData
   * 永続化データを保存する
   */
  this.putStoredData = function(flg) {
    menuAry = new Array();

    // メニューの作成
    j = 0;
    for (var i = 0; i < MaxMenuNum; i++) {
      var menu = $('#foodMenu'+i).val();
      
      if (menu == null || menu == undefined || menu.length < 1) continue;
      menuAry[j] = menu;
      j++;
    }

    // 公開範囲
    public = $('#public').val();
    
    var allDisableFlg = true;
    recommendTarget = new Object();
    if ($('#checkBreakfast').attr("checked")) {
      recommendTarget.checkBreakfast = true;
      allDisableFlg = false;
    } else {
      recommendTarget.checkBreakfast = false;
    }

    if ($('#checkLunch').attr("checked")) {
      recommendTarget.checkLunch = true;
      allDisableFlg = false;
    } else {
      recommendTarget.checkLunch = false;
    }

    if ($('#checkDinner').attr("checked")) {
      recommendTarget.checkDinner = true;
      allDisableFlg = false;
    } else {
      recommendTarget.checkDinner = false;
    }
    
    if (allDisableFlg) {
      alert('おすすめ対象は最低1つは設定して下さい。');
      return;
    }
    
    if (flg == undefined || flg == null) {
      $.postData('/appdata/@viewer/@self', {
        'foodMenusData': menuAry,
        'public' : public,
        'recommendTarget' : recommendTarget,
        'lastRecommend' : lastRecommend
      }, function () { alert('設定完了'); });
    } else {
      $.postData('/appdata/@viewer/@self', {
        'foodMenusData': menuAry,
        'public' : public,
        'recommendTarget' : recommendTarget,
        'lastRecommend' : lastRecommend
      }, function () {});
    }
    
    this.showBySetting();
  };
};

function dispContentTab()
{
}

function dispFoodMenuTab()
{
  if (!client.isOwner()) {
    $('#foodMenus').html('アプリをインストールして下さい。');
    return ;
  }
}

function dispRecommendMenuTab()
{
  if (!client.isOwner()) {
    $('#recommendMenuTab').html('アプリをインストールして下さい。');
    return ;
  }
}

function dispOtherTab()
{
}


function getRecommendFood()
{
  var tmpAry = new Array();

  if (menuAry.length < 3) {
    alert("メニューがかぶっちゃうよ！");
    return ;
  }

  for (var i = 0; i < menuAry.length; i++) {
    tmpAry[i] = menuAry[i];
  }
  
  var index = 0;
  var length = tmpAry.length;
  
  lastRecommend = new Object();

  index = Math.floor(Math.random() * length);
  var breakfast = tmpAry[index];
  lastRecommend.breakfast = breakfast;
  tmpAry.splice(index, 1);

  index = Math.floor(Math.random() * (length - 1));
  var lunch = tmpAry[index];
  lastRecommend.lunch = lunch;
  tmpAry.splice(index, 1);

  index = Math.floor(Math.random() * (length - 2));
  var dinner = tmpAry[index];
  lastRecommend.dinner = dinner;
  tmpAry.splice(index, 1);
  
  lastRecommend.date = getNowDate();
  
  $('#breakfastData').html(breakfast);
  $('#lunchData').html(lunch);
  $('#dinnerData').html(dinner);
  $('#lastdateData').html(lastRecommend.date);

  client.putStoredData(true);
}

function getNowDate()
{
  d = new Date();
  var year = d.getYear();
  if (year < 2000) {
    year = 1900 + year;
  }
  return year + '年' + (d.getMonth() + 1) + '月' + d.getDate() + '日' + d.getHours() + '時' + d.getMinutes() + '分';
}